#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
#include<set>
using namespace std;

class Solution {
public:
    int swimInWater(vector<vector<int>>& grid) {
         int minValue = INT16_MAX;
        int pathValue = INT16_MIN;
        set<pair<int,int>> S;
        DFS(grid,0,0,S,pathValue,minValue);
        return minValue;
    }
    void DFS(vector<vector<int>>& grid,int i,int j,set<pair<int,int>> S,int pathValue,int& minValue){
        if(i<0||i>=grid.size()||j<0||j>=grid[0].size()||S.find(make_pair(i,j))!=S.end()){
            return ;        
        }
        if(i==grid.size()-1&&j==grid[0].size()-1){
            minValue = min(minValue,pathValue);
            return;
        }
        if(pathValue>=minValue){
            return;
        }
        S.insert(make_pair(i,j));
        pathValue = max(pathValue,grid[i][j]);
        DFS(grid,i-1,j,S,i-1>=0&&i-1<grid.size()?max(pathValue,grid[i-1][j]):pathValue,minValue);
        DFS(grid,i+1,j,S,i+1>=0&&i+1<grid.size()?max(pathValue,grid[i+1][j]):pathValue,minValue);
        DFS(grid,i,j-1,S,j-1>=0&&j-1<grid[0].size()?max(pathValue,grid[i][j-1]):pathValue,minValue);
        DFS(grid,i,j+1,S,j+1>=0&j+1<grid[0].size()?max(pathValue,grid[i][j+1]):pathValue,minValue);
    }
};

int main(){
    vector<vector<int>> grid = {{0,1,2,3,4},{24,23,22,21,5},{12,13,14,15,16},{11,17,18,19,20},{10,9,8,7,6}};
    Solution S;
    cout<<S.swimInWater(grid)<<endl;
}

